package com.goods.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.goods.common.enums.system.UserTypeEnum;
import com.goods.common.model.business.*;
import com.goods.common.model.system.Department;
import com.goods.common.model.system.User;
import com.goods.common.utils.CategoryTreeBuilder;
import com.goods.common.utils.ListPageUtils;
import com.goods.common.vo.business.*;
import com.goods.common.vo.system.PageVO;
import com.goods.controller.mapper.*;
import com.goods.service.businessService;
import com.goods.system.mapper.ProductStockMapper;
import com.google.gson.JsonArray;
import org.apache.ibatis.session.RowBounds;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class businessServiceImpl implements businessService {
    @Autowired
    private SupplierMapper supplierMapper;
    @Autowired
    private ProductCategoryMapper productCategoryMapper;
    @Autowired
    private InStockMapper inStockMapper;
    @Autowired
    private ConsumerMapper consumerMapper;
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private OutStockMapper outStockMapper;


    //入库记录分页
    @Override
    public PageVO<InStockVO> findInStockList(Integer pageNum, Integer pageSize, InStockVO inStockVO) {
        PageHelper.startPage(pageNum, pageSize);
        Example o = new Example(InStock.class);
        List<InStock> inStocks = inStockMapper.selectAll();
       List<InStock> inStockArrayList = new ArrayList<>();
        for (InStock inStock : inStocks) {
            Date createTime = inStock.getCreateTime();
            Example.Criteria criteria = o.createCriteria();
            if(inStockVO.getInNum()!=null && !"".equals(inStockVO.getInNum())){
                o.createCriteria().andLike("inNum","%"+inStockVO.getInNum()+"%");
            }
            if(null!=inStockVO.getType() &&!"".equals(inStockVO.getType())){
                o.createCriteria().andLike("type","%"+inStockVO.getType()+"%");
            }
            if(null!=inStockVO.getStatus() &&!"".equals(inStockVO.getStatus())){
                o.createCriteria().andLike("status","%"+inStockVO.getStatus()+"%");
            }
            if(null!=inStockVO.getStartTime() && !"".equals(inStockVO.getStartTime()) && null!=inStockVO.getEndTime() && !"".equals(inStockVO.getEndTime())){
                 if(inStockVO.getStartTime().compareTo(createTime)<0&&inStockVO.getEndTime().compareTo(createTime)>0){
                     o.createCriteria().andLike("createTime",createTime+"%");
                 }else {
                     continue;
                 }
                List<InStock> inStocks1 = inStockMapper.selectByExample(o);
                 if (inStocks1!=null&&!"".equals(inStocks1)){
                     for (InStock stock : inStocks1) {
                         inStockArrayList.add(stock);
                     }
                 }
            }
        }
        List<InStockVO> inStockVOS = new ArrayList<>();
        if(!CollectionUtils.isEmpty(inStockArrayList)){
            for (InStock inStock : inStockArrayList) {
                Supplier supplier = new Supplier();
                supplier.setId(inStock.getSupplierId());
                Supplier supplier1 = supplierMapper.selectOne(supplier);
                InStockVO i = new InStockVO();
                BeanUtils.copyProperties(inStock,i);
                i.setSupplierName(supplier1.getName());
                i.setPhone(supplier1.getPhone());
                inStockVOS.add(i);
            }
        }
        PageInfo<InStock> inStockPageInfo = new PageInfo<>(inStockArrayList);
        return new PageVO<>(inStockPageInfo.getTotal(),inStockVOS);
    }

    //物资来源分页查询
    @Override
    public PageVO<SupplierVO> baseTrademark(Integer pageNum, Integer pageSize, SupplierVO supplierVO) {
        PageHelper.startPage(pageNum, pageSize);
        Example o = new Example(Supplier.class);
        if (supplierVO != null ) {
            if(supplierVO.getName()!=null&&!"".equals(supplierVO.getName())){
                o.createCriteria().andLike("name", "%" +supplierVO.getName() + "%");
            }
            if(supplierVO.getAddress()!=null&&!"".equals(supplierVO.getAddress())){
                o.createCriteria().andLike("address", "%" +supplierVO.getAddress() + "%");
            }
            if(supplierVO.getContact()!=null&&!"".equals(supplierVO.getContact())){
                o.createCriteria().andLike("contact", "%" +supplierVO.getContact() + "%");
            }
        }
        List<Supplier> supplierList = supplierMapper.selectByExample(o);
        List<SupplierVO> supplierListVo = new ArrayList<>();
        if(!CollectionUtils.isEmpty(supplierList)){
            for (Supplier supplier : supplierList) {
                SupplierVO s = new SupplierVO();
                BeanUtils.copyProperties(supplier,s);
                supplierListVo.add(s);
            }
        }
        PageInfo<Supplier> info = new PageInfo<>(supplierList);
        return new PageVO<>(info.getTotal(), supplierListVo);
    }
    //物质类别分页查询
    @Override
    public PageVO<ProductCategoryTreeNodeVO> categoryTree(Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<ProductCategory> productCategories = productCategoryMapper.selectAll();
        List<ProductCategoryTreeNodeVO> collect = productCategories.stream().map(productCategory -> {
            ProductCategoryTreeNodeVO p = new ProductCategoryTreeNodeVO();
            BeanUtils.copyProperties(productCategory,p);
            return p;
        }).collect(Collectors.toList());
       /* ArrayList<ProductCategoryTreeNodeVO> productCategoryVO = new ArrayList<>();
        if(!CollectionUtils.isEmpty(productCategories)){
            for (ProductCategory productCategory : productCategories) {
                ProductCategoryTreeNodeVO p = new ProductCategoryTreeNodeVO();
                BeanUtils.copyProperties(productCategory,p);
                productCategoryVO.add(p);
            }
        }
        List<ProductCategoryTreeNodeVO> build = CategoryTreeBuilder.build(productCategoryVO);
        List<ProductCategoryTreeNodeVO> page = ListPageUtils.page(build, pageSize.intValue(), pageNum.intValue());
        return new PageVO<ProductCategoryTreeNodeVO>(build.size(),page);*/
        List<ProductCategoryTreeNodeVO> build = CategoryTreeBuilder.build(collect);
        List<ProductCategoryTreeNodeVO> page = ListPageUtils.page(build,pageSize.intValue(), pageNum.intValue());
        return new PageVO<ProductCategoryTreeNodeVO>(build.size(),page);
    }
    //物资类别删除
    @Override
    public void deleteProductCategory(Integer id) {
        productCategoryMapper.deleteByPrimaryKey(id);
    }
    //物资类别的父分类
    @Override
    public List<ProductCategoryTreeNodeVO> getParentCategoryTree() {
        List<ProductCategory> productCategories = productCategoryMapper.selectAll();
        ArrayList<ProductCategoryTreeNodeVO> productCategoryVO = new ArrayList<>();
        if(!CollectionUtils.isEmpty(productCategories)){
            for (ProductCategory productCategory : productCategories) {
                ProductCategoryTreeNodeVO p = new ProductCategoryTreeNodeVO();
                BeanUtils.copyProperties(productCategory,p);
                productCategoryVO.add(p);
            }
        }
        List<ProductCategoryTreeNodeVO> build = CategoryTreeBuilder.build(productCategoryVO);
        return build;
    }
    //物资类别的添加
    @Override
    public void addProductCategory(ProductCategory productCategory) {
        productCategory.setCreateTime(new Date());
        productCategoryMapper.insert(productCategory);
    }
    //物资去处
    @Override
    public  PageVO<ConsumerVO> findConsumerList(Integer pageNum, Integer pageSize, ConsumerVO consumerVo) {
        PageHelper.startPage(pageNum,pageSize);
        Example o = new Example(Consumer.class);
        if(consumerVo.getName() !=null && !"".equals(consumerVo.getName())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("name","%"+consumerVo.getName()+"%");
        }
        if(consumerVo.getContact() !=null && !"".equals(consumerVo.getContact())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("contact","%"+consumerVo.getContact()+"%");
        }
        if(consumerVo.getAddress() !=null && !"".equals(consumerVo.getAddress())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("address","%"+consumerVo.getAddress()+"%");
        }
        List<Consumer> consumers = consumerMapper.selectByExample(o);
        List<ConsumerVO> collect = consumers.stream().map(consumer1 -> {
            ConsumerVO c = new ConsumerVO();
            BeanUtils.copyProperties(consumer1,c);
            return c;
        }).collect(Collectors.toList());
        List<ConsumerVO> page = ListPageUtils.page(collect, pageSize, pageNum);
      //  PageInfo<ConsumerVO> consumerVOPageInfo = new PageInfo<>(collect);
        return new PageVO<ConsumerVO>(page.size(),page);
        //return new PageVO<>(consumerVOPageInfo.getTotal(),collect);
    }
    //物资资料
    @Override
    public PageVO<ProductVO> findProductList(Integer pageNum, Integer pageSize, ProductVO productVO) {
        PageHelper.startPage(pageNum, pageSize);
        Example o = new Example(Product.class);
       if(null!= productVO.getName()&&!"".equals(productVO.getName())){
           o.createCriteria().andLike("name","%"+productVO.getName()+"%");
        }
       if(null!= productVO.getStatus()&&!"".equals(productVO.getStatus())){
           o.createCriteria().andLike("status","%"+productVO.getStatus()+"%");
        }
        Example.Criteria criteria = o.createCriteria();
        criteria.andNotEqualTo("status",0);
        List<Product> products = productMapper.selectByExample(o);
        List<ProductVO> collect = products.stream().map(product -> {
            ProductVO productVO1 = new ProductVO();
            BeanUtils.copyProperties(product,productVO1);
            return  productVO1;
        }).collect(Collectors.toList());
        PageInfo<Product> productPageInfo = new PageInfo<>(products);
      return new PageVO<>(productPageInfo.getTotal(), collect);
    }
    //添加物资资料保存数据
    @Override
    public void addIntoStock(InStockVO inStockVO) {
        InStock inStock = new InStock();
        inStock.setInNum(UUID.randomUUID().toString());
        inStock.setType(inStockVO.getType());
        inStock.setCreateTime(new Date());
        inStock.setRemark(inStockVO.getRemark());
        inStock.setStatus(2);
        List<Object> products = inStockVO.getProducts();
        if(!CollectionUtils.isEmpty(products)){
            for (int i = 0; i < products.size(); i++) {
                JSONArray jsonArray = new JSONArray(products);
                Integer productNumber = (Integer) jsonArray.getJSONObject(i).get("productNumber");
                inStock.setProductNumber(productNumber);
            }
        }
        Supplier supplier = new Supplier();
        supplier.setName(inStockVO.getName());
        supplier.setAddress(inStockVO.getAddress());
        supplier.setEmail(inStockVO.getEmail());
        supplier.setPhone(inStockVO.getPhone());
        supplier.setSort(inStockVO.getSort());
        supplier.setContact(inStockVO.getContact());
        supplier.setCreateTime(new Date());
        int insert = supplierMapper.insert(supplier);
        inStock.setSupplierId(supplier.getId());
        inStockMapper.insert(inStock);
    }
    //物资去处删除
    @Override
    public void DeleteConsumer(Integer id) {
        consumerMapper.deleteByPrimaryKey(id);
    }
    //物资去处修改（回显数据）
    @Override
    public Consumer consumerEdit(Integer id) {
        Consumer consumer = consumerMapper.selectByPrimaryKey(id);
        return consumer;
    }
    //物资去处修改（保存数据）
    @Override
    public void consumerUpdate(Consumer consumer) {
        consumer.setModifiedTime(new Date());
        consumerMapper.updateByPrimaryKey(consumer);
    }
    //物资去处添加
    @Override
    public void consumerAdd(Consumer consumer) {
        consumer.setCreateTime(new Date());
        consumer.setSort(1);
        consumerMapper.insert(consumer);
    }
    //物资资料修改状态(回复)1--->0
    @Override
    public void productBack(Integer id) {
        Product product = new Product();
        product.setId(id.longValue());
        product.setStatus(0);
       /* Product product1 = productMapper.selectByPrimaryKey(id);
        Integer status = product1.getStatus();
        if(status==1){
            product.setStatus(0);
        }*/
        productMapper.updateByPrimaryKeySelective(product);

    }
    // 物资资料修改状态(添加到回收站)0--->1
    @Override
    public void productRemove(Integer id) {
        Product product = new Product();
        product.setId(id.longValue());
        product.setStatus(1);
       /* Product product1 = productMapper.selectByPrimaryKey(id);
        Integer status = product1.getStatus();
        if(status==1){
            product.setStatus(0);
        }*/
        productMapper.updateByPrimaryKeySelective(product);
    }
    //物资资料修改状态(通过审核)2--->0
    @Override
    public void productPublish(Integer id) {
        Product product = new Product();
        product.setId(id.longValue());
        product.setStatus(0);
       /* Product product1 = productMapper.selectByPrimaryKey(id);
        Integer status = product1.getStatus();
        if(status==1){
            product.setStatus(0);
        }*/
        productMapper.updateByPrimaryKeySelective(product);
    }
    //物资资料添加
    @Override
    public void productAdd(Product product) {
        product.setCreateTime(new Date());
        product.setStatus(2);
        productMapper.insert(product);
    }
    //物资类别的修改(回显)
    @Override
    public ProductCategory productCategoryEdit(Integer id) {
        ProductCategory productCategory = productCategoryMapper.selectByPrimaryKey(id);
        return productCategory;
    }
    //物资类别的修改(保存修改)
    @Override
    public void productCategoryUpdate(Integer id, ProductCategory productCategory) {
        productCategory.setCreateTime(new Date());
        productCategoryMapper.updateByPrimaryKey(productCategory);
    }
    //物资来源添加
    @Override
    public void supplierAdd(Supplier supplier) {
        supplier.setCreateTime(new Date());
        supplierMapper.insert(supplier);

    }
    //物资来源去修改（回显）
    @Override
    public Supplier supplierEdit(Integer id) {
      return   supplierMapper.selectByPrimaryKey(id);
    }
    //物资来源去修改（保存数据）
    @Override
    public void supplierUpdate(Supplier supplier) {
        supplier.setModifiedTime(new Date());
        supplierMapper.updateByPrimaryKey(supplier);

    }
    //物资来源 删除(真删除)
    @Override
    public void deleteSupplier(Integer id) {
      supplierMapper.deleteByPrimaryKey(id);
    }

    //发放记录分页
    @Override
    public PageVO<OutStockVO> findOutStockList(Integer pageNum, Integer pageSize, OutStockVO outStockVO) {
        PageHelper.startPage(pageNum,pageSize);
        Example o = new Example(OutStock.class);
        if(outStockVO.getOutNum() !=null && !"".equals(outStockVO.getOutNum())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("outNum","%"+outStockVO.getOutNum()+"%");
        }
        if(outStockVO.getType() !=null && !"".equals(outStockVO.getType())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("type","%"+outStockVO.getType()+"%");
        }
        if(outStockVO.getStatus() !=null && !"".equals(outStockVO.getStatus())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("status","%"+outStockVO.getStatus()+"%");
        }
        List<OutStock> outStocks = outStockMapper.selectByExample(o);
        List<OutStockVO> collect = outStocks.stream().map(outStock -> {
            OutStockVO c = new OutStockVO();
            BeanUtils.copyProperties(outStock,c);
            return c;
        }).collect(Collectors.toList());
        List<OutStockVO> page = ListPageUtils.page(collect, pageSize, pageNum);
        return new PageVO<OutStockVO>(page.size(),page);
    }
    //物资库存分页
    @Override
    public PageVO<ProductStockVO> findProductStocks(Integer pageNum, Integer pageSize, ProductStockVO productStockVO) {
        PageHelper.startPage(pageNum,pageSize);
        Example o = new Example(ProductStock.class);
        if(productStockVO.getName() !=null && !"".equals(productStockVO.getName())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("name","%"+productStockVO.getName()+"%");
        }
      /*  if(productStockVO.getType() !=null && !"".equals(productStockVO.getType())){
            //如果传过来的查询条件不为空，进行Like模糊查询
            o.createCriteria().andLike("type","%"+productStockVO.getType()+"%");
        }*/
        List<ProductStock> productStocks = productStockMapper.selectByExample(o);
        List<ProductStockVO> collect = productStocks.stream().map(productStock -> {
            ProductStockVO c = new ProductStockVO();
            BeanUtils.copyProperties(productStock,c);
            return c;
        }).collect(Collectors.toList());
        List<ProductStockVO> page = ListPageUtils.page(collect, pageSize, pageNum);
        return new PageVO<ProductStockVO>(page.size(),page);
    }
    //健康打卡
    @Override
    public void healthReport(Health health) {
      /*  health.setCreateTime(new Date());

        healthMapper.insert(health);*/
    }

    @Autowired
    private ProductStockMapper productStockMapper;
    @Autowired
    private HealthMapper healthMapper;
}
